<?php

require_once 'Framework/Controller/Action.php';
require_once 'application/models/User/Admin.php';
require_once 'application/models/User/Self.php';

class UserController extends Framework_Controller_Action

{ 
	
	private $_admin;
	private $_adminNum;
	private $_conf;
	
    public function init()
    {
    	$this->_conf = Framework_Registry::get('config');
        $this->_admin = new User_Admin();
		$this->view->adminnum = $this->_adminNum = $this->session->get('adminnum');
		if (!$this->session->get('authorize'))	{
			$this->_redirect('/admin/');
		}
    }
    
	public function adminAction()
	{
		if ($this->session->get('adminnum')>1) {
			$this->_redirect("/index/error/");
		}
		$page = $this->_getParam(0,0);
		$l = $page; 
		$p = $onpage = $this->_conf->admin->on_page;
		$this->view->current_page="admin";
		$admins = $this->_admin->getAllAdmins(1);
		$this->view->admins = $admins;
		$this->view->uri = '/admin/user/admin/';
		$this->view->pages = User_Admin::getTotalRows();
		$this->view->page = $page; 
		$this->render();
	}
	
	public function moderatorAction()
	{
		if ($this->session->get('adminnum')>2)	{
			$this->_redirect("/index/error/");
		}
		$this->view->current_page="moder";
		$admins = $this->_admin->getAllAdmins(2);
		$this->view->admins = $admins;
		$this->render();
	}
	
	public function animatorAction()
	{
		$this->view->current_page="anim";
		$admins = $this->_admin->getAllAdmins(3);
		$this->view->admins = $admins;
		$this->render();
	}
	
    public function indexAction()
    {
    	
        $this->render();
    }
    
    public function addAction()
    {         
		$group = User_Admin::getWho($this->_getParam(0));
		if ($group['groupId']<$this->_adminNum) $this->_redirect("/index/error/");
		$this->view->current_page = $this->view->who = $group['who'];
		$this->render();
    }
	
	 private function _registrationValid($form)
    {
        $errors = array();

        if (empty($form['username']) ||
            empty($form['password']) ||
            empty($form['password_again']) ||
            empty($form['mail']) ||
            empty($form['sex']) ||
            empty($form['born']) ||
            empty($form['number']) ||
            empty($form['country']) ||
            empty($form['city'])) {
                $errors['empty'] = 'Required fields are empty';
        }
        if (!preg_match("[^[а-яa-z\s_']*$]siu", $form['username'])) {
            $errors['username'] = 'Name should be a-z only';
        } else if (User_Self::findUserIdByLogin($form['username'])) {
            $errors['username'] = 'Unavailable login';
        }          
        if ($form['password'] != $form['password_again']) {
            $errors['password'] = 'Password missmatch';
        }
        if (strlen($form['password']) < 6) {
            $errors['password'] = 'Password too short';
        }
        
        if (!@checkdate($form['month'], $form['day'], $form['year'])) {
            $errors['born'] = 'Incorrect';
        }
        if (!preg_match('[^\d{10,}$]si', $form['number'])) {
            $errors['number'] = 'Incorrect (only numbers, 10 min)';
        }
        if (!preg_match('[\w+@\w+.\w{2,4}]si', $form['mail'])) {
            $errors['mail'] = 'Incorrect email';
        } else if (User_Self::findUserIdByMail($form['mail'])) {
            $errors['mail'] = 'This mail alredy in use';
        }
        if (sizeof($errors)) { return $errors; }
        
        return false;
    }
	
	public function adduserAction()
	{
		$this->view->current_page="user";
		if ($this->_request->getMethod() != 'POST') { // Not a POST request
            // Записываем лицензию в сессию, для того чтобы при ошибках сабмита формы не перекинуло на главную
            $this->session->set('reg', true);
            // Если регистрировался ставим флаг
            if ($reg = $this->session->get('registration')) {
                $this->view->registration = $reg;
                $this->view->user_id = $this->session->get('user_id');
                $this->session->set('registration', false);
            } else {
                $this->view->month = 'empty';
                $this->view->year  = 'empty';
                $this->view->day   = 'empty';
            }   
        } else {
            // Handle log-in form
            $form = get_value($this->getRequest()->getParam('form'));
            $form['month'] = $this->getRequest()->getParam('Date_Month');
            $form['day']   = $this->getRequest()->getParam('Date_Day');
            $form['year']  = $this->getRequest()->getParam('Date_Year');
            $form['born'] = $form['year']  . '-'
                          . $form['month'] . '-'
                          . $form['day'];
            if (($error = $this->_registrationValid($form)) !== false) { // Not valid
                $this->view->error = $error;
                $this->view->form  = $form;
                $this->view->month = $this->getRequest()->getParam('Date_Month');
                $this->view->year  = $this->getRequest()->getParam('Date_Year');
                $this->view->day   = $this->getRequest()->getParam('Date_Day');
                                
            } else { // Valid registration
                if ($user = User_Self::createUser($form)) {               
                    // >> Создаем папку пользователя
					$uploads = '/uploads';
					$user_id = $user->getUserId();
                    $folder  = floor($user_id/1000);
                    @mkdir($this->getRequest()->get('DOCUMENT_ROOT') . $uploads . '/' . $folder);
                    @mkdir($this->getRequest()->get('DOCUMENT_ROOT') . $uploads . '/' . $folder . '/' . $user->getUserId());
                    @mkdir($this->getRequest()->get('DOCUMENT_ROOT') . $uploads . '/' . $folder . '/' . $user->getUserId() . '/min');
                    
                    $path = $uploads . '/' . $folder . '/' . $user->getUserId();
                    // <<
                    $user->setPath($path);
					$this->session->set('error','');
                } else {
					$this->session->set('error','error adding user');
				}
                $this->_redirect('/admin/user/result/');
            }
        }
        
        $this->render();
	}
	
	public function resultAction()
	{
		$this->view->current_page="user";
		if ($msg = $this->session->get('error')){
			$this->view->message = $msg;	
		}
		$this->render();
	}
	
	public function addnewAction()
	{
		$group = User_Admin::getWho($this->_getParam(0));
		if ($group['groupId']<$this->_adminNum) $this->_redirect("/index/error/");
		$this->view->current_page = $this->view->who = $group['who'];
		$login = get_value($this->getRequest()->name);
		$pass = get_value($this->getRequest()->pass);
		$pass2 = get_value($this->getRequest()->pass2);
		$error = false;
		if ($pass!==$pass2) {
			$error = true;
			$this->view->message = "Password not match";
		}
		if (strlen($pass)<6) {
			$this->view->message = "Password too short (min 6 characters)";
			$error = true;
		}
		if ( ($login == '') || (strlen($login)<4) ) {
			$this->view->message = "Invalid login (min 4 characters)";
			$error = true;
		}
		
		if (!$error) {
			if ($this->_admin->setNewAdmin($login,$pass,$group['groupId']))
				$this->view->message = "New {$group['who']} has been added: $login";
			else $this->view->message = "Sorry, we have an adding error 
											(maybe dublicate names)?";
		}
		$this->render();
	}
	
	/**
	 * удаляем кого-то из админов
	 * @return 
	 */
	public function delAction()
	{	
		$group = User_Admin::getWho($this->_getParam(0));
		$this->view->current_page= $group['who'];
		if ($group['groupId']<$this->_adminNum) $this->_redirect("/index/error/");
		$id = get_value($this->_getParam(1,0));
		$this->view->who = $group['who'];
		if ($id) {
			if ($this->_admin->setDelete($id))
				$this->view->message = "Deleted";
			else $this->view->message = "Sorry, we have a delete error (incorrect params)?";
		}	
		else $this->view->message = "Sorry, we have a delete error (incorrect params)?";
		$this->render();
	}
	
	/**
	 * удаляем кого-то из пользователей
	 * @return 
	 */
	public function delUserAction()
	{
		$id =  intval(get_value($this->_getParam(0,0)));
		if ($id) {
			if (User_Admin::setUserDelete($id))
				$this->view->message = 'Deleted';
			else $this->view->message = 'Sorry, we have a delete error (incorrect params?)';
		}
		else $this->view->message = 'Sorry, we have a delete error (incorrect params?)';
		$this->render();
	}
}